import React from 'react';
import {Table} from 'antd';
import PropTypes from 'prop-types';
import routes from './routes';
import {Link} from 'react-router-dom';
import {PAGINATION_OPTIONS, TABLE, COMMON_TABLE_QUERY_FAIL_TEXT, COMMON_TABLE_EMPTY_TEXT,
    DATETIME_FORMAT, FIXED_COLUMN_WIDTH} from '../constants';
import {injectIntl} from './intl';
import {conventEnumValueToString, formatDateTime, formatAmount} from '../utils';
import DropdownMenu from 'Shared/components/DropdownMenu';
import {currency, partBackOrderStatus} from '../Enum';
import {PERMISSION} from './constants';
import {hasPermissions} from './utils';

const basePath = fetch.basePath || '';
const url = '/#/dcs/parts/partBackOrder/';

export class TablePanel extends React.PureComponent {
    constructor(props) {
        super(props);
        this.onChangeSort = this.onChangeSort.bind(this);
    }
    onChangeSort = (pagination, filters, sorter) => {
        this.props.onChangeSort({
            pageIndex: pagination.current - 1,
            pageSize: pagination.pageSize,
            sortedColumnKey: sorter.columnKey,
            sortedOrder: sorter.order,
        });
    };
    render() {
        const colums = [
            {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.code',
                    defaultMessage: '编号'
                }),
                dataIndex: 'code',
                width: '100px',
                sorter: true,
                sortOrder: this.props.sortedColumnKey === 'code' && this.props.sortedOrder,
                render: (text, record) => <Link to={routes.detail.format(record.id)} >{text}</Link>
            }, {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.brandCode',
                    defaultMessage: '品牌'
                }),
                dataIndex: 'brandCode',
                sorter: true,
                sortOrder: this.props.sortedColumnKey === 'brandCode' && this.props.sortedOrder,
                render: (text, record) => (record.brandCode) + record.brandName
            }, {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.saleOrderCode',
                    defaultMessage: '订单编号'
                }),
                dataIndex: 'saleOrderCode',
                sorter: true,
                sortOrder: this.props.sortedColumnKey === 'saleOrderCode' && this.props.sortedOrder,
            }, {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.saleOrderTypeName',
                    defaultMessage: '订单类型'
                }),
                dataIndex: 'saleOrderTypeName',
                sorter: true,
                sortOrder: this.props.sortedColumnKey === 'saleOrderTypeName' && this.props.sortedOrder,
            }, {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.orderAmount',
                    defaultMessage: 'PI金额'
                }),
                dataIndex: 'orderAmount',
                render: text => formatAmount(text)
            }, {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.currency',
                    defaultMessage: '币种'
                }),
                dataIndex: 'currency',
                render: text => conventEnumValueToString(currency, text)
            }, {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.orderDate',
                    defaultMessage: '提报日期'
                }),
                dataIndex: 'orderDate',
                sorter: true,
                sortOrder: this.props.sortedColumnKey === 'orderDate' && this.props.sortedOrder,
                render: text => formatDateTime(text, DATETIME_FORMAT)
            }, {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.status',
                    defaultMessage: '缺货单状态'
                }),
                dataIndex: 'status',
                sorter: true,
                sortOrder: this.props.sortedColumnKey === 'status' && this.props.sortedOrder,
                render: text => conventEnumValueToString(partBackOrderStatus, text)
            }];
        if(!this.props.isDealerUser)
            colums.splice(2, 0, ...[
                {
                    title: this.props.intl.formatMessage({
                        id: 'tablePanel.column.dealerCode',
                        defaultMessage: '总代ERP号'
                    }),
                    dataIndex: 'dealerCode',
                    sorter: true,
                    sortOrder: this.props.sortedColumnKey === 'dealerCode' && this.props.sortedOrder,
                },
            ]);
        colums.push({
            title: this.props.intl.formatMessage({
                id: 'tablePanel.column.action',
                defaultMessage: '操作'
            }),
            dataIndex: 'action',
            width: FIXED_COLUMN_WIDTH,
            fixed: 'right',
            render: (t, r) => {
                const menus = [
                    {
                        id: PERMISSION.confirmor,
                        children: (
                            <a key="confirmor" href={`${basePath}${url}${r.id}/confirmor?code=${r.saleOrderCode}&dealerId=${r.dealerId}&dealerCode=${r.dealerCode}&dealerName=${r.dealerName}&brandId=${r.brandId}&status=${r.status}`}>{
                                this.props.intl.formatMessage({
                                    id: 'tablePanel.operation.confirmor',
                                    defaultMessage: '确认'
                                })
                            }</a>
                        ),
                        hidden: !(hasPermissions(this.props.permissions, PERMISSION.confirmor) && hasPermissions(r.options, PERMISSION.confirmor))
                    }, {
                        id: PERMISSION.close,
                        children: (
                            <a key="close" href={`${basePath}${url}${r.id}/close?code=${r.saleOrderCode}&dealerId=${r.dealerId}&dealerCode=${r.dealerCode}&dealerName=${r.dealerName}&brandId=${r.brandId}&status=${r.status}`}>{
                                this.props.intl.formatMessage({
                                    id: 'tablePanel.operation.close',
                                    defaultMessage: '关闭'
                                })
                            }</a>
                        ),
                        hidden: !(hasPermissions(this.props.permissions, PERMISSION.close) && hasPermissions(r.options, PERMISSION.close))
                    }
                ];
                return <DropdownMenu key={r.id} menus={menus} primaryLength={1} id={r.id} />;
            }
        });
        const pagination = {
            total: this.props.total,
            pageSize: this.props.pageSize,
            current: this.props.pageIndex + 1,
            ...PAGINATION_OPTIONS
        };
        const locale = {
            emptyText: this.props.errorMessage ? COMMON_TABLE_QUERY_FAIL_TEXT : COMMON_TABLE_EMPTY_TEXT
        };
        
        return (
            <div>
                <Table
                    className="white-space-nowrap"
                    columns={colums}
                    dataSource={this.props.list}
                    onChange={this.onChangeSort}
                    rowKey="id"
                    pagination={pagination}
                    loading={this.props.loading}
                    locale={locale}
                    {...TABLE} />
            </div>
        );
    }
}

TablePanel.propTypes = {
    errorMessage: PropTypes.string.isRequired,
    list: PropTypes.array.isRequired,
    loading: PropTypes.bool.isRequired,
    permissions: PropTypes.array.isRequired,
    total: PropTypes.number.isRequired,
    onChangeSort: PropTypes.func.isRequired,
    intl: PropTypes.object,
    isDealerUser: PropTypes.bool,
    pageIndex: PropTypes.number,
    pageSize: PropTypes.number,
    refreshListData: PropTypes.func,
    sortedColumnKey: PropTypes.string,
    sortedOrder: PropTypes.string,
};

import {connect} from 'react-redux';
import selectorFactory from 'Shared/utils/immutableToJsSelectorFactory';
import {tableSearch} from './actions';

const getData = selectorFactory(['page', 'domainData', 'list', 'data']);
const getPermissions = selectorFactory(['page', 'domainData', 'permission', 'data']);
const mapStateToProps = state => ({
    list: getData(state),
    total: state.getIn(['page', 'domainData', 'list', 'total']),
    pageIndex: state.getIn(['page', 'appState', 'queryBySort', 'pageIndex']),
    pageSize: state.getIn(['page', 'appState', 'queryBySort', 'pageSize']),
    loading: state.getIn(['page', 'domainData', 'list', 'isFetching']),
    errorMessage: state.getIn(['page', 'domainData', 'list', 'message']),
    sortedColumnKey: state.getIn(['page', 'appState', 'queryBySort', 'sortedColumnKey']),
    sortedOrder: state.getIn(['page', 'appState', 'queryBySort', 'sortedOrder']),
    isDealerUser: state.getIn((['page', 'domainData', 'initData', 'isDealerUser'])),
    permissions: getPermissions(state),
});

const mapDispatchToProps = dispatch => ({
    onChangeSort: option => dispatch(tableSearch(option)),
    refreshListData: () => dispatch(tableSearch())
});

export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(TablePanel));
